import useRequest, { RequestOptions } from '@/hooks/useKRequest';
import { UseAntdTableFormUtils } from 'ahooks/es/useAntdTable';
import { useState } from 'react';

export interface RequestFormOptions extends RequestOptions {
  form?: UseAntdTableFormUtils;
}

export default (
  service: (params: any) => Promise<any>,
  options?: RequestFormOptions,
): {
  search: {
    submit: () => void;
    reset: () => void;
  };
  action: {
    add: (data: any) => void;
    update: (id: number, data: any) => void;
    delete: (id: number) => void;
  };
  props: {
    dataSource: any[];
    loading: boolean;
    pagination: {
      current: number;
      pageSize: number;
      total: number;
      totalPage: number;
      onChange: (current: number, pageSize?: number) => void;
      changeCurrent: (current: number) => void;
      changePageSize: (pageSize: number) => void;
      [key: string]: any;
    };
  };
} => {
  const [page, setPage] = useState<number>(1);
  const [limit, setLimit] = useState<number>(10);
  const [dataSource, setDataSource] = useState<any[]>([]);
  if (options?.params) {
    options.params = {
      ...options.params,
    };
  }
  if (options?.form) {
    options.params = {
      ...options.params,
      ...options.form.getFieldsValue(),
    };
  }
  const { data, loading, run } = useRequest(service, {
    ...options,
    params: {
      page,
      limit,
      ...options?.params,
    },
    onSuccess: data => {
      setDataSource(data.data.items);
    },
  });

  return {
    search: {
      submit: () => {
        let params = {};
        if (options?.form) {
          params = {
            ...options.form.getFieldsValue(),
          };
        }
        run(params);
      },
      reset: () => {},
    },
    action: {
      add: data => {
        dataSource.unshift(data);
        setDataSource([...dataSource]);
      },
      update: (id, data) => {
        const idx = dataSource.findIndex(_ => _.id === id);
        if (idx > -1) {
          dataSource.splice(idx, 1, { ...dataSource[idx], ...data });
          setDataSource([...dataSource]);
        }
      },
      delete: id => {
        const idx = dataSource.findIndex(_ => _.id === id);
        if (idx > -1) {
          dataSource.splice(idx, 1);
          setDataSource([...dataSource]);
        }
      },
    },
    props: {
      dataSource: dataSource,
      loading,
      pagination: {
        current: page,
        pageSize: limit,
        total: data?.data?.total ?? 0,
        totalPage: 10,
        onChange: (page, size?: number) => {
          setPage(page);
          if (size) {
            setLimit(size);
          }
          run({
            page,
            limit,
            ...options?.params,
          });
        },
        changeCurrent: (current: number) => {},
        changePageSize: (pageSize: number) => {},
      },
    },
  };
};
